<?php
// public/materials/index.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';

require_login();
$user = current_user();

// Access: admin/hr/trainer can manage (upload/edit/delete)
// employees can only view list
$canManage = in_array($user['role'], ['admin','hr','trainer'], true);

global $pdo;

$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

$params = [];
$where = '';
if ($q !== '') {
    $where = "WHERE m.title LIKE :q_title OR t.title LIKE :q_training";
    $params[':q_title'] = "%$q%";
    $params[':q_training'] = "%$q%";
  }

// If trainer, show only their own uploaded materials
if ($user['role'] === 'trainer') {
  $where .= ($where ? " AND " : "WHERE ")."m.uploaded_by = :uid";
  $params[':uid'] = (int)$user['id'];
}

$sqlCount = "SELECT COUNT(*) AS c
             FROM materials m
             JOIN training t ON t.id = m.training_id
             $where";
$stmt = $pdo->prepare($sqlCount);
$stmt->execute($params);
$total = (int)$stmt->fetch()['c'];
$pages = max(1, (int)ceil($total / $perPage));

$sql = "SELECT m.id, m.title, m.type, m.file_path, m.video_url, 
               m.created_at, t.title AS training_title, u.name AS uploader
        FROM materials m
        JOIN training t ON t.id = m.training_id
        JOIN users u ON u.id = m.uploaded_by
        $where
        ORDER BY m.created_at DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

render_header('Training Materials', 'materials');
$flash = get_flash();
if ($flash): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type']) ?>">
    <?= htmlspecialchars($flash['message']) ?>
  </div>
<?php endif; ?>

<div class="card">
  <div class="card-header d-flex align-items-center">
    <form class="form-inline ml-auto" method="get">
      <div class="input-group">
        <input class="form-control" name="q" placeholder="Search title/training" value="<?= htmlspecialchars($q) ?>">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary"><i class="fas fa-search"></i></button>
        </div>
      </div>
    </form>
    <?php if ($canManage): ?>
      <a href="upload.php" class="btn btn-primary ml-2"><i class="fas fa-upload"></i> Upload Material</a>
    <?php endif; ?>
  </div>

  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0">
        <thead>
          <tr>
            <th style="width:60px;">ID</th>
            <th>Title</th>
            <th>Training</th>
            <th>Type</th>
            <th>Uploader</th>
            <th style="width:200px;">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="6" class="text-center text-muted p-4">No materials found.</td></tr>
          <?php else: foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><?= htmlspecialchars($r['title']) ?></td>
              <td><?= htmlspecialchars($r['training_title']) ?></td>
              <td><span class="badge badge-info"><?= strtoupper($r['type']) ?></span></td>
              <td><?= htmlspecialchars($r['uploader']) ?></td>
              <td class="data-actions">
                <?php if ($r['type'] === 'pdf'): ?>
                  <a class="btn btn-sm btn-outline-secondary" target="_blank" href="/ldp/uploads/<?= htmlspecialchars($r['file_path']) ?>">
                    <i class="fas fa-file-pdf"></i> View
                  </a>
                <?php elseif ($r['type'] === 'video'): ?>
                  <a class="btn btn-sm btn-outline-info" target="_blank" href="<?= htmlspecialchars($r['video_url']) ?>">
                    <i class="fas fa-video"></i> Watch
                  </a>
                <?php endif; ?>

                <?php if ($canManage): ?>
                  <a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int)$r['id'] ?>"><i class="fas fa-edit"></i> Edit</a>
                  <form method="post" action="delete.php" class="d-inline" onsubmit="return confirm('Delete this material?');">
                    <?= csrf_field(); ?>
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i> Delete</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if ($pages > 1): ?>
  <div class="card-footer">
    <ul class="pagination mb-0">
      <?php for ($i=1; $i <= $pages; $i++): ?>
        <li class="page-item <?= $i===$page?'active':'' ?>">
          <a class="page-link" href="?<?= http_build_query(['q'=>$q,'page'=>$i]) ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </div>
  <?php endif; ?>
</div>

<?php render_footer();
